package messages

import (
	"github.com/patrickmn/go-cache"
	"golang.org/x/time/rate"
	"time"
)

// LimitInTimeSender 限制指定时间内发送
type LimitInTimeSender struct {
	limiter *cache.Cache
	sec     int
}

func NewTimeInLimitSender(sec int) *LimitInTimeSender {
	return &LimitInTimeSender{
		limiter: cache.New(time.Minute*10, time.Minute*10),
		sec:     sec,
	}
}

func (s *LimitInTimeSender) Allow(target string) bool {
	key := "limiter_" + target
	value, find := s.limiter.Get(key)
	var limiter *rate.Limiter
	if find {
		limiter = value.(*rate.Limiter)
	} else {
		limiter = rate.NewLimiter(1, s.sec+1)
		s.limiter.Set(key, limiter, cache.DefaultExpiration)
	}

	return limiter.AllowN(time.Now(), s.sec)
}

func (s *LimitInTimeSender) Send(target string, msg string) error {
	return nil
}

type noneSender int

func NewNoneSender() *noneSender {
	var a noneSender
	return &a
}

func (s *noneSender) Send(target string, msg string) error {
	return nil
}

func (s *noneSender) Allow(target string) bool {
	return true
}
